package com.web;

import org.apache.logging.log4j.jul.Log4jBridgeHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.sql.DataSource;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;

@EnableScheduling
@SpringBootApplication
public class WebServerApplication {
    private static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    private static void removeDefaultRootHandler() {
        if (isWindows()) {
            System.setProperty("log4j.skipJansi", "false");
        }

        try {
            java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
            Handler[]                handlers   = rootLogger.getHandlers();
            if (handlers.length == 1 && handlers[0] instanceof ConsoleHandler) {
                rootLogger.removeHandler(handlers[0]);
            }
        } catch (Throwable ex) {
            // Ignore and continue
        }
    }

    public static void main(String[] args) {
        removeDefaultRootHandler();
        Log4jBridgeHandler.install(false, null, true);
        Logger log = Logger.getLogger(WebServerApplication.class.getName());
        log.info("Hello, World!");

        SpringApplication.run(WebServerApplication.class, args);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("bye!")));
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(SpringUtils.getBean(DataSource.class));
    }
}

